import torch
import torch.nn as nn
import torch.nn.functional as F

class SELayer_1d(nn.Module):
    def __init__(self, channel, reduction=16):
        super(SELayer_1d, self).__init__()
        # self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.avg_pool = nn.AdaptiveAvgPool1d(1)
        self.fc = nn.Sequential(
            nn.Linear(channel, channel // reduction, bias=False),
            nn.ReLU(inplace=True),
            nn.Linear(channel // reduction, channel, bias=False),
            nn.Sigmoid()
        )

    def forward(self, x):
        b, c, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1)
        return x * y.expand_as(x)

class BasicConv1d(nn.Module):
    def __init__(self, in_planes, out_planes, kernel_size, stride, padding=0):
        super(BasicConv1d, self).__init__()
        self.conv = nn.Conv1d(
            in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
        self.bn = nn.BatchNorm1d(out_planes, eps=.001)
        self.relu = nn.ReLU(inplace=False)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        x = self.relu(x)
        return x


class Mixed_5b(nn.Module):
    def __init__(self):
        super(Mixed_5b, self).__init__()

        self.branch0 = BasicConv1d(192, 96, kernel_size=1, stride=1)

        self.branch1 = nn.Sequential(
            BasicConv1d(192, 48, kernel_size=1, stride=1),
            BasicConv1d(48, 64, kernel_size=5, stride=1, padding=2)
        )

        self.branch2 = nn.Sequential(
            BasicConv1d(192, 64, kernel_size=1, stride=1),
            BasicConv1d(64, 96, kernel_size=3, stride=1, padding=1),
            BasicConv1d(96, 96, kernel_size=3, stride=1, padding=1)
        )

        self.branch3 = nn.Sequential(
            nn.AvgPool1d(3, stride=1, padding=1, count_include_pad=False),
            BasicConv1d(192, 64, kernel_size=1, stride=1)
        )

    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        x2 = self.branch2(x)
        x3 = self.branch3(x)
        out = torch.cat((x0, x1, x2, x3), 1)
        return out


class Block35(nn.Module):
    def __init__(self, scale=1.0):
        super(Block35, self).__init__()

        self.scale = scale

        self.branch0 = BasicConv1d(320, 32, kernel_size=1, stride=1)

        self.branch1 = nn.Sequential(
            BasicConv1d(320, 32, kernel_size=1, stride=1),
            BasicConv1d(32, 32, kernel_size=3, stride=1, padding=1)
        )

        self.branch2 = nn.Sequential(
            BasicConv1d(320, 32, kernel_size=1, stride=1),
            BasicConv1d(32, 48, kernel_size=3, stride=1, padding=1),
            BasicConv1d(48, 64, kernel_size=3, stride=1, padding=1)
        )

        self.conv2d = nn.Conv1d(128, 320, kernel_size=1, stride=1)
        self.relu = nn.ReLU(inplace=False)

    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        x2 = self.branch2(x)
        out = torch.cat((x0, x1, x2), 1)
        out = self.conv2d(out)
        out = out * self.scale + x
        out = self.relu(out)
        return out


class Mixed_6a(nn.Module):
    def __init__(self):
        super(Mixed_6a, self).__init__()

        self.branch0 = BasicConv1d(320, 384, kernel_size=3, stride=2)

        self.branch1 = nn.Sequential(
            BasicConv1d(320, 256, kernel_size=1, stride=1),
            BasicConv1d(256, 256, kernel_size=3, stride=1, padding=1),
            BasicConv1d(256, 384, kernel_size=3, stride=2)
        )

        self.branch2 = nn.MaxPool1d(3, stride=2)

    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        x2 = self.branch2(x)
        out = torch.cat((x0, x1, x2), 1)
        return out


class Block17(nn.Module):
    def __init__(self, scale=1.0):
        super(Block17, self).__init__()

        self.scale = scale

        self.branch0 = BasicConv1d(1088, 192, kernel_size=1, stride=1)

        self.branch1 = nn.Sequential(
            BasicConv1d(1088, 128, kernel_size=1, stride=1),
            BasicConv1d(128, 160, kernel_size=7, stride=1, padding=3),
            BasicConv1d(160, 192, kernel_size=7, stride=1, padding=3)
        )

        self.conv2d = nn.Conv1d(384, 1088, kernel_size=1, stride=1)
        self.relu = nn.ReLU(inplace=False)

    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        out = torch.cat((x0, x1), 1)
        out = self.conv2d(out)
        out = out * self.scale + x
        out = self.relu(out)
        return out


class Mixed_7a(nn.Module):
    def __init__(self):
        super(Mixed_7a, self).__init__()

        self.branch0 = nn.Sequential(
            BasicConv1d(1088, 256, kernel_size=1, stride=1),
            BasicConv1d(256, 384, kernel_size=3, stride=2)
        )

        self.branch1 = nn.Sequential(
            BasicConv1d(1088, 256, kernel_size=1, stride=1),
            BasicConv1d(256, 288, kernel_size=3, stride=2)
        )

        self.branch2 = nn.Sequential(
            BasicConv1d(1088, 256, kernel_size=1, stride=1),
            BasicConv1d(256, 288, kernel_size=3, stride=1, padding=1),
            BasicConv1d(288, 320, kernel_size=3, stride=2)
        )

        self.branch3 = nn.MaxPool1d(3, stride=2)

    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        x2 = self.branch2(x)
        x3 = self.branch3(x)
        out = torch.cat((x0, x1, x2, x3), 1)
        return out


class Block8(nn.Module):

    def __init__(self, scale=1.0, no_relu=False):
        super(Block8, self).__init__()

        self.scale = scale

        self.branch0 = BasicConv1d(2080, 192, kernel_size=1, stride=1)

        self.branch1 = nn.Sequential(
            BasicConv1d(2080, 192, kernel_size=1, stride=1),
            BasicConv1d(192, 224, kernel_size=3, stride=1, padding=1),
            BasicConv1d(224, 256, kernel_size=3, stride=1, padding=1)
        )

        self.conv2d = nn.Conv1d(448, 2080, kernel_size=1, stride=1)
        self.relu = None if no_relu else nn.ReLU(inplace=False)

    def forward(self, x):
        x0 = self.branch0(x)
        x1 = self.branch1(x)
        out = torch.cat((x0, x1), 1)
        out = self.conv2d(out)
        out = out * self.scale + x
        if self.relu is not None:
            out = self.relu(out)
        return out

def adaptive_pool_feat_mult(pool_type='avg'):
    if pool_type == 'catavgmax':
        return 2
    else:
        return 1

class SelectAdaptivePool1d(nn.Module):
    """Selectable global pooling layer with dynamic input kernel size
    """
    def __init__(self, output_size=1, pool_type='avg', flatten=False):
        super(SelectAdaptivePool1d, self).__init__()
        self.output_size = output_size
        self.pool_type = pool_type
        self.flatten = flatten
        self.pool = nn.AdaptiveAvgPool1d(output_size)

    def forward(self, x):
        x = self.pool(x)
        if self.flatten:
            x = x.flatten(1)
        return x

    def feat_mult(self):
        return adaptive_pool_feat_mult(self.pool_type)

    def __repr__(self):
        return self.__class__.__name__ + ' (' \
               + 'output_size=' + str(self.output_size) \
               + ', pool_type=' + self.pool_type + ')'

class SE_InceptionResnetV2(nn.Module):
    def __init__(self, num_classes=1001, in_chans=3, drop_rate=0., global_pool='avg'):
        super(SE_InceptionResnetV2, self).__init__()
        self.drop_rate = drop_rate
        self.num_classes = num_classes
        self.num_features = 1536

        self.conv2d_1a = BasicConv1d(in_chans, 32, kernel_size=3, stride=2)
        self.conv2d_2a = BasicConv1d(32, 32, kernel_size=3, stride=1)
        self.conv2d_2b = BasicConv1d(32, 64, kernel_size=3, stride=1, padding=1)
        self.maxpool_3a = nn.MaxPool1d(3, stride=2)
        self.conv2d_3b = BasicConv1d(64, 80, kernel_size=1, stride=1)
        self.conv2d_4a = BasicConv1d(80, 192, kernel_size=3, stride=1)
        self.maxpool_5a = nn.MaxPool1d(3, stride=2)
        self.mixed_5b = Mixed_5b()
        self.repeat = nn.Sequential(
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320),
            Block35(scale=0.17),
            SELayer_1d(channel=320)
        )
        self.mixed_6a = Mixed_6a()
        self.repeat_1 = nn.Sequential(
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088),
            Block17(scale=0.10),
            SELayer_1d(channel=1088)
        )
        self.mixed_7a = Mixed_7a()
        self.repeat_2 = nn.Sequential(
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080),
            Block8(scale=0.20),
            SELayer_1d(channel=2080)
        )
        self.block8 = Block8(no_relu=True)
        self.conv2d_7b = BasicConv1d(2080, self.num_features, kernel_size=1, stride=1)
        self.global_pool = SelectAdaptivePool1d(pool_type=global_pool)
        # NOTE some variants/checkpoints for this model may have 'last_linear' as the name for the FC
        self.classif = nn.Linear(self.num_features * self.global_pool.feat_mult(), num_classes)

    def get_classifier(self):
        return self.classif

    def reset_classifier(self, num_classes, global_pool='avg'):
        self.global_pool = SelectAdaptivePool1d(pool_type=global_pool)
        self.num_classes = num_classes
        if num_classes:
            num_features = self.num_features * self.global_pool.feat_mult()
            self.classif = nn.Linear(num_features, num_classes)
        else:
            self.classif = nn.Identity()

    def forward_features(self, x):
        x = self.conv2d_1a(x)
        x = self.conv2d_2a(x)
        x = self.conv2d_2b(x)
        x = self.maxpool_3a(x)
        x = self.conv2d_3b(x)
        x = self.conv2d_4a(x)
        x = self.maxpool_5a(x)
        x = self.mixed_5b(x)
        x = self.repeat(x)
        x = self.mixed_6a(x)
        x = self.repeat_1(x)
        x = self.mixed_7a(x)
        x = self.repeat_2(x)
        x = self.block8(x)
        x = self.conv2d_7b(x)
        return x

    def forward(self, x):
        x = self.forward_features(x)
        x = self.global_pool(x).flatten(1)
        if self.drop_rate > 0:
            x = F.dropout(x, p=self.drop_rate, training=self.training)
        x = self.classif(x)
        return x